<template>
  <div>
    <van-nav-bar title="城市列表" class="van-nav-bar-my">
      <template #left>
        <van-icon color="#fff" name="arrow-left" @click="$router.back()" />
      </template>
    </van-nav-bar>
    <van-index-bar
      :index-list="indexList"
      v-if="allObj.A && allObj.A.length > 0"
    >
      <template v-for="(item, index) in allObj">
        <van-index-anchor :index="index" :key="index">
          <span v-if="index === '#'">当前</span>
          <span v-else-if="index === '热'">热门城市</span>
          <span v-else>{{ index }}</span>
        </van-index-anchor>
        <template v-if="item.length > 0">
          <van-cell
            v-for="item1 in item"
            :key="item1.id"
            :title="item1.label"
            @click="changeCity(item1)"
          />
        </template>
        <template v-else>
          <van-cell :key="index * 100">暂无数据</van-cell>
        </template>
      </template>
    </van-index-bar>
  </div>
</template>

<script>
import { getCity, getHotCity } from '@/api/homepage'
export default {
  name: 'city-page',
  async created() {
    const res = await getCity()
    const zxc = res.data.body
    const hotList = await getHotCity()
    const asd = hotList.data.body
    console.log(asd)
    const allObj = {
      '#': [
        {
          label: '上海',
          value: 'AREA|dbf46d32-7e76-1196',
          pinyin: 'shanghai',
          short: 'sh'
        }
      ],
      热: [],
      A: [],
      B: [],
      C: [],
      D: [],
      E: [],
      F: [],
      G: [],
      H: [],
      I: [],
      J: [],
      K: [],
      L: [],
      M: [],
      N: [],
      O: [],
      P: [],
      Q: [],
      R: [],
      S: [],
      T: [],
      U: [],
      V: [],
      W: [],
      X: [],
      Y: [],
      Z: []
    }
    allObj.hot = asd
    // console.log(res)
    zxc.forEach((item) => {
      const key = item.short[0].toUpperCase()
      allObj[key].push(item)
    })
    this.allObj = allObj
  },
  data() {
    return {
      indexList: [
        '#',
        '热',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ],
      hotList: [],
      allObj: {}
    }
  },
  methods: {
    changeCity(city) {
      console.log(city)
      window.localStorage.setItem('city', JSON.stringify(city))
      this.$router.push('/homepage')
    }
  }
}
</script>

<style scoped lang="less">
.van-nav-bar-my {
  background-color: #58b67f;
  ::v-deep .van-nav-bar__title {
    color: #fff;
  }
}
::v-deep .van-index-anchor,
.van-cell {
  padding-left: 20px;
}

::v-deep .van-index-anchor {
  color: #ccc;
  font-size: 20px;
}

::v-deep .van-index-bar__index--active {
  background-color: #58b67f;
  color: #fff;
}
</style>
